package com.tea.servlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

import com.tea.entity.CartItem;
import com.tea.entity.User;
import com.tea.service.CartService;
import com.tea.service.impl.CartServiceImpl;
import com.tea.util.URLUtil;

@WebServlet("/cart")
public class CartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws javax.servlet.ServletException, java.io.IOException {
        doPost(req, resp);
    }

    private CartService cartService = new CartServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws javax.servlet.ServletException, java.io.IOException {
        req.setCharacterEncoding("UTF-8");
        String action = req.getParameter("action");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        // 验证用户登录状态
        if (user == null) {
            String redirectUrl = URLUtil.buildRedirectUrl("/login.jsp", "message", "请先登录再操作购物车");
            resp.sendRedirect(redirectUrl);
            return;
        }

        try {
            Long userId = user.getId();
            switch (action) {
                case "add":
                    handleAdd(req, userId);
                    break;
                case "update":
                    handleUpdate(req, userId);
                    break;
                case "remove":
                    handleRemove(req, userId);
                    break;
            }
            // 从数据库重新获取最新购物车数据
            Map<Long, CartItem> cart = cartService.getUserCart(userId);
            double totalPrice = cartService.calculateTotalPrice(cart);
            session.setAttribute("cart", cart);
            session.setAttribute("totalPrice", totalPrice);
            resp.sendRedirect("/cart.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("errorMsg", "购物车操作失败: " + e.getMessage());
            resp.sendRedirect("/cart.jsp");
        }
    }

    private void handleAdd(HttpServletRequest req, Long userId) throws Exception {
        Long productId = Long.parseLong(req.getParameter("productId"));
        int quantity = Integer.parseInt(req.getParameter("quantity"));
        cartService.addToCart(userId, productId, quantity);
    }

    private void handleUpdate(HttpServletRequest req, Long userId) throws Exception {
        Long productId = Long.parseLong(req.getParameter("productId"));
        int newQuantity = Integer.parseInt(req.getParameter("quantity"));
        cartService.updateCartItem(userId, productId, newQuantity);
    }

    private void handleRemove(HttpServletRequest req, Long userId) throws Exception {
        Long productId = Long.parseLong(req.getParameter("productId"));
        cartService.removeFromCart(userId, productId);
    }

    // 计算总价逻辑已迁移至CartService
    private void calculateTotalPrice(Map<Long, CartItem> cart, HttpSession session) {
        double total = cartService.calculateTotalPrice(cart);
        session.setAttribute("totalPrice", total);
    }


}